package com.usian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.mapper.*;
import com.usian.mq.MQSender;
import com.usian.pojo.*;
import com.usian.redis.RedisClient;
import com.usian.service.OrderService;
import com.usian.utils.JsonUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Value("${ORDER_ID_KEY}")
    private String ORDER_ID_KEY;

    @Value("${ORDER_ID_BEGIN}")
    private Long ORDER_ID_BEGIN;

    @Value("${ORDER_ITEM_ID_KEY}")
    private String ORDER_ITEM_ID_KEY;

    @Resource
    private RedisClient redisClient;

    @Resource
    private TbOrderMapper tbOrderMapper;

    @Resource
    private TbOrderItemMapper tbOrderItemMapper;

    @Resource
    private TbOrderShippingMapper tbOrderShippingMapper;
    @Resource
    TbItemMapper tbItemMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private MQSender mqSender;
    @Resource
    LocalMessageMapper localMessageMapper;
    @Override
    public Long insertOrder(OrderInfo orderInfo) {
        //1、解析orderInfo
        TbOrder tbOrder = orderInfo.getTbOrder();
        TbOrderShipping tbOrderShipping = orderInfo.getTbOrderShipping();
        //使用JsonUtils把json转成Java
        List<TbOrderItem> tbOrderItemList =
                JsonUtils.jsonToList(orderInfo.getOrderItem(), TbOrderItem.class);
        //2、保存订单信息
        if(!redisClient.exists(ORDER_ID_KEY)){
            redisClient.set(ORDER_ID_KEY,ORDER_ID_BEGIN);
        }
        //设置orderid并自增
        Long orderId = redisClient.incr(ORDER_ID_KEY, 1L);
        tbOrder.setOrderId(orderId.toString());
        Date date = new Date();
        //设置创建时间和修改时间
        tbOrder.setCreateTime(date);
        tbOrder.setUpdateTime(date);
        //1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭
        //设置状态并添加
        tbOrder.setStatus(1);
        tbOrderMapper.insertSelective(tbOrder);
        //3、保存明细信息
        //查看oderItemId在redis是否未null
        if(!redisClient.exists(ORDER_ITEM_ID_KEY)){
            //如果没有就创建一个
            redisClient.set(ORDER_ITEM_ID_KEY,0);
        }
        for (int i = 0; i < tbOrderItemList.size(); i++) {
            //设置oderItemId并自增
            Long oderItemId = redisClient.incr(ORDER_ITEM_ID_KEY, 1L);
            TbOrderItem tbOrderItem =  tbOrderItemList.get(i);
            tbOrderItem.setId(oderItemId.toString());
            tbOrderItem.setOrderId(orderId.toString());
            tbOrderItemMapper.insertSelective(tbOrderItem);
        }
        //4、保存物流信息
        tbOrderShipping.setOrderId(orderId.toString());
        tbOrderShipping.setCreated(date);
        tbOrderShipping.setUpdated(date);
        tbOrderShippingMapper.insertSelective(tbOrderShipping);
        //保存本地消息记录
        LocalMessage localMessage = new LocalMessage();
        localMessage.setTxNo(UUID.randomUUID().toString());
        localMessage.setOrderNo(orderId.toString());
        localMessage.setState(0);
        localMessageMapper.insertSelective(localMessage);

        //发布消息到mq，完成扣减库存
        mqSender.sendMsg(localMessage);
        //发布消息到mq，完成扣减库存
        //amqpTemplate.convertAndSend("order_exchage","order.add", orderId);
        //5、返回订单id
        return orderId;

    }
    //、查询超时订单
    @Override
    public List<TbOrder> selectOverTimeTbOrder() {
        return tbOrderMapper.selectOvertimeOrder();
    }
    //修改订单表的状态 逻辑删除关闭超时订单
    @Override
    public void updateOverTimeTbOrder(TbOrder tbOrder) {
        tbOrder.setStatus(6);
        Date date = new Date();
        tbOrder.setCloseTime(date);
        tbOrder.setEndTime(date);
        tbOrder.setUpdateTime(date);
        tbOrderMapper.updateByPrimaryKeySelective(tbOrder);
    }
    //3、把超时订单中的商品库存数量加回去
    @Override
    public void updateTbItemByOrderId(String orderId) {
        //1、通过orderId查询List<TbOrderItem>
        QueryWrapper<TbOrderItem> tbOrderItemQueryWrapper = new QueryWrapper<>();
        tbOrderItemQueryWrapper.eq("order_id",orderId);
        List<TbOrderItem> tbOrderItemList = tbOrderItemMapper.selectList(tbOrderItemQueryWrapper);
        for (int i = 0; i < tbOrderItemList.size(); i++) {
            TbOrderItem tbOrderItem =  tbOrderItemList.get(i);
            //2、修改商品库存
            TbItem tbItem =
                    tbItemMapper.selectByPrimaryKey(Long.valueOf(tbOrderItem.getItemId()));
            tbItem.setNum(tbItem.getNum()+tbOrderItem.getNum());
            tbItem.setUpdated(new Date());
            tbItemMapper.updateById(tbItem);
        }
    }

}
